package cn.phecda.boot.tenant.data.jpa;

import cn.phecda.boot.common.lang.model.TenantContext;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;

import java.util.Map;

/**
 * <p> 默认租户ID选择器 </p>
 *
 * @author : wanpinwei
 */
@Slf4j
public class TenantCurrentIdentifierResolver implements CurrentTenantIdentifierResolver<String>, HibernatePropertiesCustomizer {

    @Override
    public String resolveCurrentTenantIdentifier() {
        String currentTenantId = TenantContext.get();
        log.debug("|Phecda Boot Tenant|- Current identifier [{}]", currentTenantId);
        return currentTenantId;
    }

    @Override
    public boolean validateExistingCurrentSessions() {
        return true;
    }

    @Override
    public void customize(Map<String, Object> hibernateProperties) {
        hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
    }
}
